//
//  CarouselAdvertiseView.m
//  PhotoScrollView
//
//  Created by X and 冷悦 on 16/3/17.
//  Copyright © 2016年 URANUS. All rights reserved.
//

#import "CarouselAdvertiseView.h"
#import "Masonry.h"
#import <objc/runtime.h>

@interface CarouselAdvertiseView () <UIScrollViewDelegate>

@property (nonatomic, assign)NSInteger currentIndex;

@property (nonatomic, assign)NSInteger contentCount;

@property (nonatomic, strong)UIView *leftView;

@property (nonatomic, strong)UIView *rightView;

@property (nonatomic, strong)UIView *currentView;

@property (nonatomic, strong)UIPageControl *pageControl;

@property (nonatomic, strong)NSArray *contents;

@property (nonatomic, strong)NSTimer *timer;

@property (nonatomic, strong)UIScrollView *scrollView;


@end

@implementation CarouselAdvertiseView

#pragma mark - Initialize
- (instancetype)init{
    if (self = [super init]) {
        [self setupConstraints];
        [self setupInitialParams];
    }
    
    return self;
}

#pragma mark - Life Circle
- (void)dealloc{
    DDLogInfo(@"in dealloc");
}

#pragma mark - UIScrollViewDelegate
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self stopTimer];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self startTimer];
    [self updateViewForDragging];
}

#pragma mark - Event Response
- (void)timerAction:(NSTimer *)timer{
    if (self.views != nil) {
        DDLogInfo(@"滚动");
        self.currentIndex = (self.currentIndex + 1) % self.views.count;
        [self updateScrollViewAnimated:YES];
    }
}

#pragma mark - Private
- (void)setupConstraints{
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.width.height.equalTo(self);
    }];
    
    [self.leftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(self.scrollView);
        make.width.height.equalTo(self);
        make.right.equalTo(self.currentView.mas_left);
    }];
    
    [self.currentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView);
        make.width.height.equalTo(self.leftView);
        make.right.equalTo(self.rightView.mas_left);
    }];
    
    [self.rightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.equalTo(self.scrollView);
        make.width.height.equalTo(self.currentView);
    }];
    
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self);
        make.height.equalTo(self).multipliedBy(0.15);
    }];
}

- (void)updateScrollViewAnimated:(BOOL)animated{
    NSInteger viewsCount = self.views.count;
    self.pageControl.currentPage = self.currentIndex;
    NSInteger leftViewIndex = (self.currentIndex + viewsCount - 1) % viewsCount;
    NSInteger rightViewIndex = (self.currentIndex + 1) % viewsCount;
    UIView *leftView = self.views[leftViewIndex];
    UIView *currentView = self.views[self.currentIndex];
    UIView *rightView = self.views[rightViewIndex];
    [self setContentView:self.leftView withContent:leftView];
    [self setContentView:self.currentView withContent:currentView];
    [self setContentView:self.rightView withContent:rightView];
    
    if (_delegate != nil && [_delegate respondsToSelector:@selector(pageScrollToPresentView:)]) {
        DDLogInfo(@"当前项：%ld------数组中当前项:%ld",self.currentIndex,[self.views indexOfObject:currentView]);
       [_delegate pageScrollToPresentView:currentView];
    }
    
    if (animated == YES) {
        [self.scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
        [self.scrollView setContentOffset:CGPointMake(CGRectGetWidth(self.frame), 0) animated:YES];
    }else{
        [self.scrollView setContentOffset:CGPointMake(CGRectGetWidth(self.frame), 0) animated:NO];
    }
}

- (void)setupInitialParams{
    self.isAnimation = YES;
    self.pageEnabled = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.delegate = self;
}

- (void)disableTimer{
    if (self.timer != nil) {
        [self.timer invalidate];
    }
}

- (void)setContentView:(UIView *)view withContent:(UIView *)content{
    NSArray *subViews = view.subviews;
    
    for (UIView *subView in subViews) {
        [subView removeFromSuperview];
    }
    
    [view addSubview:content];
    
    [content mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.width.height.equalTo(view);
    }];
}

- (void)setContentViewAtIndex:(NSInteger)index withView:(UIView *)view{
    if (index == 0) {
        [self.leftView addSubview:view];
    } else if (index == 1) {
        [self.currentView addSubview:view];
    } else {
        [self.rightView addSubview:view];
    }
}

- (void)updateViewForDragging{
    NSInteger viewsCount = self.views.count;
    
    if (viewsCount > 0) {
        CGPoint offset = self.scrollView.contentOffset;
        CGFloat width = CGRectGetWidth(self.scrollView.frame);
        
        if (offset.x >= width) {
            self.currentIndex = (self.currentIndex + 1) % self.views.count;
        } else if (offset.x < width) {
            self.currentIndex = (self.currentIndex + viewsCount - 1) % viewsCount;
        }
        
        [self updateScrollViewAnimated:NO];
    }
}


- (void)stopTimer{
    if (self.timer != nil) {
        [self.timer setFireDate:[NSDate distantFuture]];
    }
}

- (void)startTimer{
    if (self.timer != nil && self.isAnimation == YES) {
        [self.timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:self.timeInterval]];
    }
}

#pragma mark - Public
- (void)updateCarouselAdvertiseViewContentToCurrentViewIndex:(NSInteger)index{
    
    if (index < _views.count) {
        self.currentIndex = index;
        [self updateScrollViewAnimated:NO];
    }else{
        NSAssert(NO, @"updateCarouselAdvertiseViewContentToCurrentViewIndex方法调用失败，传入的index超出views数组长度");
    }
}


#pragma mark - Getters
- (NSArray *)contents{
    if (_contents == nil) {
        _contents = @[self.leftView, self.currentView, self.rightView];
    }
    
    return _contents;
}

- (UIView *)leftView{
    if (_leftView == nil) {
        _leftView = [UIView new];
        [self.scrollView addSubview:_leftView];
    }
    
    return _leftView;
}

- (UIView *)currentView{
    if (_currentView == nil) {
        _currentView = [UIView new];
        [self.scrollView addSubview:_currentView];
    }
    
    return _currentView;
}

- (UIView *)rightView{
    if (_rightView == nil) {
        _rightView = [UIView new];
        [self.scrollView addSubview:_rightView];
    }
    
    return _rightView;
}

- (UIScrollView *)scrollView{
    if (_scrollView == nil) {
        _scrollView = [UIScrollView new];
        _scrollView.pagingEnabled = YES;
        [self addSubview:_scrollView];
    }
    
    return _scrollView;
}

- (UIPageControl *)pageControl{
    if (_pageControl == nil) {
        _pageControl = [UIPageControl new];
        _pageControl.pageIndicatorTintColor=[UIColor colorWithRed:193/255.0 green:219/255.0 blue:249/255.0 alpha:1.0];
        _pageControl.currentPageIndicatorTintColor=[UIColor colorWithRed:0.0 green:150/255.0 blue:1.0 alpha:1.0];
        [self insertSubview:_pageControl aboveSubview:self.scrollView];
    }
    
    return _pageControl;
}

#pragma mark - Setters
- (void)setIsAnimation:(BOOL)isAnimation{
    _isAnimation = isAnimation;
    
    if (_isAnimation == NO) {
        [self stopTimer];
    } else {
        [self startTimer];
    }
}

- (void)setViews:(NSArray *)views{
    _views = views;
    NSInteger viewsCount = views.count;
    self.pageControl.numberOfPages = viewsCount;
    self.currentIndex = 0;
    [self updateScrollViewAnimated:NO];
}

- (void)setTimeInterval:(NSTimeInterval)timeInterval{
    _timeInterval = timeInterval;
    [self disableTimer];
    
    if (timeInterval > 0) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
        [self.timer fire];
    }
}

- (void)setPageEnabled:(BOOL)pageEnabled{
    _pageEnabled = pageEnabled;
    
    if (pageEnabled == YES) {
        if ([self.pageControl superview] == nil) {
            [self insertSubview:self.pageControl aboveSubview:self.scrollView];
            [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.equalTo(self);
                make.height.equalTo(self).multipliedBy(0.15);
            }];
        }
    } else {
        [self.pageControl removeFromSuperview];
    }
}


@end
